﻿using Caliburn.Micro;
using SD.Infrastructure.WPF.Caliburn.Aspects;
using SD.Infrastructure.WPF.Caliburn.Base;
using SD.Infrastructure.WPF.Extensions;
using SD.Infrastructure.WPF.Models;
using SD.IOC.Core.Mediators;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.Extensions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using SlamDunk.MES.Client.ViewModels.ExecutionPlan;
using SlamDunk.MES.IAppService.DTOs.Inputs;
using SlamDunk.MES.IAppService.DTOs.Outputs.PlanContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.QualityContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.ResourceContext;
using SlamDunk.MES.IAppService.Interfaces;
using SlamDunk.ValueObjects.Enums;

namespace SlamDunk.MES.Client.ViewModels.ExecutionPlanInspection
{
    /// <summary>
    /// 创建成品质检ViewModel
    /// </summary>
    public class AddViewModel : ScreenBase
    {
        #region # 字段及构造器
        /// <summary>
        /// 质量管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IQualityContract> _iQualityContract;

        /// <summary>
        /// 作业管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IExecutionContract> _iExecutionContract;

        /// <summary>
        /// 编号生成服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<INumberContract> _iNumberContract;

        /// <summary>
        /// 窗口管理器
        /// </summary>
        private readonly IWindowManager _windowManager;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public AddViewModel(ServiceProxy<IQualityContract> iQualityContract, ServiceProxy<IExecutionContract> iExecutionContract, ServiceProxy<INumberContract> iNumberContract, IWindowManager windowManager)
        {
            this._iQualityContract = iQualityContract;
            this._iExecutionContract = iExecutionContract;
            this._iNumberContract = iNumberContract;
            this._windowManager = windowManager;
        }

        #endregion

        #region 属性
        #region 质量检查编号
        /// <summary>
        /// 质量检查编号
        /// </summary>
        [DependencyProperty]
        public string InspectionNo { get; set; }
        #endregion

        #region 质量检查名称
        /// <summary>
        /// 质量检查名称
        /// </summary>
        [DependencyProperty]
        public string InspectionName { get; set; }
        #endregion

        #region 质检日期
        /// <summary>
        /// 质检日期
        /// </summary>
        [DependencyProperty]
        public DateTime? InspectedDate { get; set; }
        #endregion

        #region 作业计划
        /// <summary>
        /// 作业计划
        /// </summary>
        [DependencyProperty]
        public string ExecutionPlanName { get; set; }
        #endregion

        #region 描述
        /// <summary>
        /// 描述
        /// </summary>
        [DependencyProperty]
        public string Description { get; set; }
        #endregion

        #region 作业计划Info
        /// <summary>
        /// 作业计划Info
        /// </summary>
        [DependencyProperty]
        public ExecutionPlanInfo _executionPlanInfo { get; set; }
        #endregion

        #region 质量检查明细列表
        /// <summary>
        /// 质量检查明细列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<QualityInspectionDetailInfo> DetailParams { get; set; }
        #endregion
        #endregion

        #region 方法
        #region 初始化 —— override async Task OnInitializeAsync(CancellationToken cancellationToken)
        /// <summary>
        /// 初始化
        /// </summary>
        protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
        {
            this.DetailParams = new ObservableCollection<QualityInspectionDetailInfo>();
            this.InspectionNo = await Task.Run(() => this._iNumberContract.Channel.GenerateExecutionPlanInspectionNo());
        }
        #endregion

        #region 作业计划弹出层清理
        /// <summary>
        /// 作业计划弹出层清理
        /// </summary>
        public async void ClearExecutionPlan()
        {
            this._executionPlanInfo = new ExecutionPlanInfo();
            this.ExecutionPlanName = null;
        }
        #endregion

        #region 作业计划弹出层
        /// <summary>
        /// 作业计划弹出层
        /// </summary>
        public async void SelectExecutionPlan()
        {
            this.Busy();

            SelectExecutionPlanViewModel viewModel = ResolveMediator.Resolve<SelectExecutionPlanViewModel>();
            viewModel.Load(false, null, ExecutionPlanStatus.Completed, null);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                Wrap<ExecutionPlanInfo> executionPlanInfo = viewModel.ExecutionPlans.Where(x => x.IsChecked == true).FirstOrDefault();
                this._executionPlanInfo = executionPlanInfo.Model;
                this.ExecutionPlanName = executionPlanInfo.Model.Name;
            }
            this.Idle();
        }
        #endregion

        #region 添加质检明细
        /// <summary>
        /// 添加质检明细
        /// </summary>
        public async void Create()
        {
            if (string.IsNullOrEmpty(this.ExecutionPlanName))
            {
                MessageBox.Show("请选择作业计划信息！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            this.Busy();
            AddItemViewModel viewModel = ResolveMediator.Resolve<AddItemViewModel>();
            viewModel.Load(this.ExecutionPlanName);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                this.DetailParams.Add(new QualityInspectionDetailInfo()
                {
                    ProductInfo = new MaterialInfo() { Number = this._executionPlanInfo.ProductInfo.Number, Name = this._executionPlanInfo.ProductInfo.Name, StandardUnitNo = this._executionPlanInfo.ProductInfo.StandardUnitNo },
                    ProductId = this._executionPlanInfo.ProductId,
                    ProductionQuantity = viewModel.ProductionQuantity.Value,
                    QualifiedQuantity = viewModel.QualifiedQuantity.Value,
                    SampleQuantity = viewModel.SampleQuantity.Value,
                    Manhour = viewModel.Manhour,
                    Machinehour = viewModel.Machinehour,
                    Description = viewModel.Description
                });
            }
            this.Idle();
        }
        #endregion

        #region 删除质量检查明细
        /// <summary>
        /// 删除质量检查明细
        /// </summary>
        public async void RemoveWorkOrder(QualityInspectionDetailInfo qualityInspectionDetailInfo)
        {
            this.Busy();
            //清除单据明细缓存
            this.DetailParams.Remove(qualityInspectionDetailInfo);
            this.Idle();
        }
        #endregion

        #region 提交 —— async void Submit()
        /// <summary>
        /// 提交
        /// </summary>
        public async void Submit()
        {
            #region # 验证
            if (string.IsNullOrEmpty(this.ExecutionPlanName))
            {
                MessageBox.Show("请选择工单信息！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (this.InspectedDate == null)
            {
                MessageBox.Show("请选择质检日期！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (this.DetailParams.Count() == 0)
            {
                MessageBox.Show("质检明细不能为空！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            #endregion

            List<QualityInspectionDetailParam> qualityInspectionDetailParams = new List<QualityInspectionDetailParam>();
            foreach (var detailParam in this.DetailParams)
            {
                QualityInspectionDetailParam qualityInspectionDetailParam = new QualityInspectionDetailParam();
                qualityInspectionDetailParam.productId = detailParam.ProductId;
                qualityInspectionDetailParam.productionQuantity = detailParam.ProductionQuantity;
                qualityInspectionDetailParam.qualifiedQuantity = detailParam.QualifiedQuantity;
                qualityInspectionDetailParam.sampleQuantity = detailParam.SampleQuantity;
                qualityInspectionDetailParam.manhour = detailParam.Manhour;
                qualityInspectionDetailParam.machinehour = detailParam.Machinehour;
                qualityInspectionDetailParam.sort = detailParam.Sort;
                qualityInspectionDetailParam.description = detailParam.Description;
                qualityInspectionDetailParams.Add(qualityInspectionDetailParam);
            }
            this.Busy();
            await Task.Run(() => this._iQualityContract.Channel.CreateExecutionPlanInspect(
                  this.InspectionNo,//质量检查编号
                  this.InspectionName,//质量检查名称
                  this.InspectedDate.Value,//质检日期
                  this._executionPlanInfo.Id,//作业计划Id
                  this.Description,//描述
                  qualityInspectionDetailParams));
            await base.TryCloseAsync(true);
            this.Idle();
        }
        #endregion

        //Private
        #endregion
    }
}
